from rest_framework import serializers, exceptions
from rest_framework_simplejwt.serializers import PasswordField

from .models import User, Tenant


class UserSerializer(serializers.ModelSerializer):
    id = serializers.ReadOnlyField()
    tenant = serializers.StringRelatedField()
    roles = serializers.StringRelatedField(many=True)

    class Meta:
        model = User
        fields = (
            'id',
            'email',
            'first_name',
            'last_name',
            'tenant',
            'roles',
            'created'
        )


class RegistrationSerializer(serializers.Serializer):
    email = serializers.EmailField()
    password = PasswordField(required=True, min_length=8, max_length=64)
    first_name = serializers.CharField(required=False, default='')
    last_name = serializers.CharField(required=False, default='')

    def validate_email(self, value):
        tenant_schema_name = User.make_default_tenant_schema(value)

        try:
            tenant = Tenant.objects.get(schema_name=tenant_schema_name)
        except Tenant.DoesNotExist:
            return value

        if User.objects.filter(email=value, tenant=tenant).exists():
            raise exceptions.ValidationError(f'{value} already exists')

        return value
